package com.magic.gre.adapter;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.magic.gre.R;
import com.magic.gre.callback.BaseBannerIm;
import com.magic.gre.callback.OnBannerItemClickListener;
import com.noname.lib_base_java.glide.LoadImageUtils;
import com.noname.lib_base_java.util.PathUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Lmoumou
 * Date: 2019-01-08 09:54
 * 文件名: BannerAdapter
 * 描述:
 */
public class BannerAdapter<T extends BaseBannerIm> extends PagerAdapter {
    private Context context;
    private List<T> dataList = new ArrayList<>();
    private LayoutInflater mInflater;
    private int layoutId = R.layout.item_banner_home;
    private OnBannerItemClickListener<T> onBannerItemClickListener;

    public void setOnBannerItemClickListener(OnBannerItemClickListener<T> onBannerItemClickListener) {
        this.onBannerItemClickListener = onBannerItemClickListener;
    }

    public BannerAdapter(Context context) {
        this.context = context;
        mInflater = LayoutInflater.from(context);
    }

    public BannerAdapter(Context context, int layoutId) {
        this.context = context;
        this.layoutId = layoutId;
        mInflater = LayoutInflater.from(context);
    }


    public void setData(List<T> dataList) {
        this.dataList.clear();
        this.dataList.addAll(dataList);
    }

    @Override
    public int getCount() {
        return dataList == null ? 0 : dataList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView((View) object);
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, final int position) {
        final T t = dataList.get(position);
        View view = mInflater.inflate(layoutId, container, false);
        ImageView imageView = view.findViewById(R.id.mImageView);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onBannerItemClickListener != null) {
                    onBannerItemClickListener.onBannerItemClick(t, position);
                }
            }
        });
        LoadImageUtils.loadImage(PathUtil.imgPath(t.getBannerData().getPath()), imageView);
        container.addView(view);

        return view;
    }
}
